/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple.utils.httpclient;

import org.jboss.netty.channel.*;
import org.jboss.netty.handler.ssl.SslHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author rehak
 */
public class HTTPClientHandler<E> extends SimpleChannelUpstreamHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HTTPClientHandler.class);
    private final LinkedBlockingQueue<E> queue;
    private final boolean useSSL;

    public HTTPClientHandler(LinkedBlockingQueue<E> queue, boolean useSSL) {
        this.queue = queue;
        this.useSSL = useSSL;
    }

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            LOGGER.debug(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        if (useSSL) {
            // Get the SslHandler from the pipeline
            // which were added in SecureChatPipelineFactory.
            SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
            // Begin handshake.
            sslHandler.handshake();
        }
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        // got message
        try {
            E response = (E) e.getMessage();
            queue.put(response);
        } catch (ClassCastException cce) {
            Class cls = null;
            if (e.getMessage() != null) {
                cls = e.getMessage().getClass();
            }
            LOGGER.error("Unable to cast " + cls, cce);
        } catch (InterruptedException ex) {
            LOGGER.error("Exception while adding response to queue", ex);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        LOGGER.warn("Unexpected exception from downstream.", e.getCause());
        e.getChannel().close();
    }
}
